<script setup>
import { RouterLink, RouterView, routerKey } from 'vue-router'
import {onMounted, ref} from 'vue';
//import kaptcha from '@/assets/kaptcha.jpg'
import HelloWorld from '../components/HelloWorld.vue'
import { reactive } from 'vue';
import { computed } from 'vue';
import { isMobile } from '@/utils/validate';//引入校验js中的校验函数
//import axios from 'axios';
import http from '@/utils/request.js';//{default as http}
import { showNotify } from 'vant';
//import router from "../router";
import { useRouter } from 'vue-router'; //路由器
const router = useRouter(); //获取到 router 对象，用于编程式跳转导航
//跳转到登录页面
function toLoginView(){
router.push("/login");
}
const username=ref('');//ref声明简单类型响应式状态,username.value
const kaptcha=ref('');
const user=reactive({//reactive声明对象(数组)类型响应式状态
 phoneNum:'',
 verifyCode:'',
 smsCode:'',
 userName:'',
 password:'',
 rePassword:''
})
const checked=ref(false);//默认未选中
//const axios = require('axios/dist/node/axios.cjs'); // node
const btnRegistIsUse=computed(()=>!checked.value);//true禁用，false可用
//const onSubmit=(values)=>{
  //  console.log('submit',values);
//}
const sendSmsStatus=ref(false);//发送验证码按钮禁用状态
const countDownInterval=ref(null);
const btnSendSmsName=ref('发送验证码');
const time=ref(60);
const countDownFn=function(){//倒计时函数
   console.log('countDown......');
   if(time.value>0){
    btnSendSmsName.value=`重新发送(${time.value})`;//重新发送的时间
    time.value-=1;
   }else{
    btnSendSmsName.value='发送验证码';
    clearInterval(countDownInterval.value);//停止计时器
    time.value=0;
    sendSmsStatus.value=false;
   }
}
//情况1，页面加载之后获取图片验证码，情况2，用户点击图片验证码刷新
function flushKaptcha(){
  console.log('flushKaptcha......');
  //请求获取图片验证码接口
  http.get("/user/kaptcha?t="+Date.now(),null)
  .then(function(response){
    //处理成功情况
    kaptcha.value="data:image/jpg;base64,"+response.data.data.img;
    user.uuid=response.data.data.uuid;
    console.log('flushKaptcha.....成功返回,'+response.data.data.img);
  })
  .catch(function(error){
    //处理错误情况
    console.log('flushKaptcha.....异常返回,'+error);
  })
}
//发送短信验证码
function sendSmsCode(){
  sendSmsStatus.value=true;//将“发送短信验证码”按钮禁用
  console.log("sendSmsCode.......");
  if(user.phoneNum && user.verifyCode){//手机号、验证码不为空
    http.get("/user/smscode",{
      params:{
        uuid:user.uuid,
        verifyCode:user.verifyCode,
        phone:user.phoneNum
      }
    }).then(function(response){//本次请求浏览器的响应状态码，response.status === 200
      //处理成功情况
      //console.log('smsCode...成功返回',response);
      console.log('sendSmsCode....返回成功：',response);
      const {code,message} = response.data;
      if(200 === code){
        countDownInterval.value = setInterval(countDownFn,1000);
      }else if(10017 === code){//图片验证码错误，清空用户输入的图片验证码，并重新获取
        user.verifyCode = "";
        sendSmsStatus.value = false;//将“发送短信验证码”按钮改为 可用状态
        flushKaptcha();
        
      }
      // countDownFn.value=setInterval(countDownFn,1000);
    }).catch(function(error){
      //处理错误情况
      console.log('sendSmsCode...异常返回',error);
    });
  }else{
    console.log('手机号、验证码为空......');
  }
}
//用户注册
const onSubmit = () =>{
  console.log(user); //TODO请求后端注册接口
  http.post("/user/register",user)
  .then(function (response){
    //处理成功情况
    console.log('register....成功返回：',response.data);
    const {code,message} = response.data;
    if(200 === code){
      showNotify({type:'success',message:'注册成功' });
      setTimeout(() => {
        router.push("/login"); //使用路径 path 导航
      },1500);
      
    }else{
      showNotify({type:'danger',message});
    }
  })
  .catch(function (error){
    //处理错误情况
    console.log('register....异常返回：',error);
  });
};
const onFailed = () => {
  //
  //
  //
  showNotify({ type:'success',message:'通知内容'})
} 
onMounted(()=>{
  flushKaptcha();
})
</script>

<template>
  <header>
    <img alt="Vue logo" class="logo" src="@/assets/haojiutao.jpg" width="125" height="125" />

    <div class="wrapper">
      <HelloWorld msg="用户注册" />
    </div>
  </header>
  <van-form @submit="onSubmit" @failed="onFailed">
  <van-cell-group inset>
    <van-field
      v-model="user.phoneNum"
      name="user.PhoneNum"
      label="手机号"
      placeholder="请输入手机号"
      required
      :rules="[{ required: true, message: '请填写手机号' },{validator:isMobile,message:'手机号格式不正确'}]"
    />
    <van-field
      v-model="user.verifyCode" center clearable required
      label="图片验证码"
      placeholder="请输入图片验证码"
      
    >
    <template #button>
        <van-image width="80" height="40" @click="flushKaptcha" style=":margin-left: 10px;" :src="kaptcha"/>
    </template>
    </van-field>
      <van-field
      v-model="user.smsCode" center clearable required  
      label="短信验证码"
      placeholder="请输入短信验证码"
    >
    <template #button>
        <van-button size="small" type="primary"  :disabled="sendSmsStatus" @click="sendSmsCode">
          {{btnSendSmsName}}
        </van-button>
    </template>
    </van-field>
    <van-field
      v-model="user.userName"
      name="user.userName"
      label="真实姓名"
      placeholder="请输入真实姓名"
      required
      :rules="[{ required: true, message: '请填写用户名' }]"
    />
    <van-field
      v-model="user.userPwd"
      type="userPwd"
      name="user.userPwd"
      label="密码"
      placeholder="请输入密码"
      required
      :rules="[{ required: true, message: '请填写密码' }]"
    />
    <van-field
      v-model="user.reuserPwd"
      type="userPwd"
      name="user.userPwd"
      label="确认密码"
      placeholder="密码"
      required
      :rules="[{ required: true, message: '请填写确认密码' }]"
    />
    <van-checkbox v-model="checked"><a>阅读《用户协议》</a></van-checkbox>
  </van-cell-group>
  <div style="margin: 16px;">
    <van-button round block type="primary" native-type="submit" :disabled="btnRegistIsUse">
      立即注册
    </van-button>
  </div>
  <div style="text-align: right; margin: 10px;">
  <a href="#" @click="toLoginView">已有账号，立即登录？</a>
  </div>
</van-form>
  <RouterView />
</template>

<style scoped>
header {
  line-height: 1.5;
  max-height: 100vh;
}
.van-field{
  /**调整每一行边距 */
  padding: 16px 15px;
}

.logo {
  display: block;
  margin: 0 auto 2rem;
}

nav {
  width: 100%;
  font-size: 12px;
  text-align: center;
  margin-top: 2rem;
}

nav a.router-link-exact-active {
  color: var(--color-text);
}

nav a.router-link-exact-active:hover {
  background-color: transparent;
}

nav a {
  display: inline-block;
  padding: 0 1rem;
  border-left: 1px solid var(--color-border);
}

nav a:first-of-type {
  border: 0;
}

@media (min-width: 1024px) {
  header {
    display: flex;
    place-items: center;
    padding-right: calc(var(--section-gap) / 2);
  }

  .logo {
    margin: 0 2rem 0 0;
  }

  header .wrapper {
    display: flex;
    place-items: flex-start;
    flex-wrap: wrap;
  }

  nav {
    text-align: left;
    margin-left: -1rem;
    font-size: 1rem;

    padding: 1rem 0;
    margin-top: 1rem;
  }
}
</style>
